package com.htandroid.htandroid.tools;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

/**
 * Created by Lyn
 */
public class ToolDataProvider {
    private ArrayList<Map<String, Object>> mData;
    private int index;
    private int total;
    private int page;

    public ToolDataProvider() {
        mData = new ArrayList<Map<String, Object>>();
        page = 4; //默认一页4条数据，建议用方法setPage设定
        index = 0;
    }

    public void initData(ArrayList<Map<String, Object>> data) {
        mData.clear();
        index = 0;
        mData.addAll(data);
        countData();
    }

    //设置一页返回数据
    public void setPage(int page) {
        if (page > 0) {
            this.page = page;
        }
    }

    public void setDataByIndex(int index, Map<String, Object> data) {
        if (index < mData.size() && index >= 0) {
            mData.set(index, data);
        }
    }

    public void addData(Map<String, Object> objectMap) {
        mData.add(objectMap);
        countData();
    }

    public void countData() {
        total = mData.size() / page + 1;
    }

    public boolean hasNext() {
        return index < total;
    }

    public ArrayList<Map<String, Object>> getFirstPage() {
        index = 0;
        return getNext();
    }

    public ArrayList<Map<String, Object>> getNext() {
        ArrayList<Map<String, Object>> next = new ArrayList<Map<String, Object>>();
        if (!hasNext()) {
            return next;
        }
        int start = index * page;
        int end = (index + 1) * page > mData.size() ? mData.size() : (index + 1) * page;
        for (int i = start; i < end; i++) {
            next.add(mData.get(i));
        }
        index++;
        return next;
    }

    //搜索功能
    public ArrayList<Map<String, Object>> getSearch(String keyword) {
        ArrayList<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        keyword = keyword.trim();
        if (TextUtils.isEmpty(keyword)) {
            return result;
        }
        for (Map<String, Object> item : mData) {
            Set<String> keySet = item.keySet();
            for (String key : keySet) {
                if (key.equals("index")) {
                    continue;
                }
                String value = (String) item.get(key);
                if (value.contains(keyword)) {
                    result.add(item);
                    break;
                }
            }
        }
        return result;
    }
}
